package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Comment;
import com.example.interceptor.JwtInterceptor;
import com.example.mapper.CommentMapper;
import com.example.service.ICommentService;
import com.example.service.IUserService;
import com.example.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王鹤蒲
 * @since 2023-08-31
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    private Logger logger= LoggerFactory.getLogger(CommentServiceImpl.class);

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private IUserService iUserService;

    @Override
    public R saveComment(Comment comment) {
        if (comment.getId() == null) {
            LocalDateTime saveTime = LocalDateTime.now();
                comment.setCommentatorId(iUserService.getCurrentLoginUser().getUserId()).setCommentTime(saveTime);
            if (comment.getPid() != null) {
                Integer pid = comment.getPid();
                Comment pComment = commentMapper.selectById(pid);
             if(pComment.getOriginId()!=null){
                 comment.setOriginId(pComment.getOriginId());
             }else{
                comment.setOriginId(comment.getPid());
             }
             }
        }
        commentMapper.insert(comment);
        return R.success();
    }

    @Override
    public R deleteById(Integer id) {
        LocalDateTime deleteTime=LocalDateTime.now();
        Comment comment=commentMapper.selectById(id);
        commentMapper.updateById(new Comment().setId(comment.getId()).setDelFlag("1").setUpdateBy(iUserService.getCurrentLoginUser().getUserName()).setUpdateTime(deleteTime));
        if(comment.getPid()==null){
            LambdaUpdateWrapper<Comment> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Comment::getOriginId,id);
            lambdaUpdateWrapper.set(Comment::getDelFlag,"1");
            lambdaUpdateWrapper.set(Comment::getUpdateBy,iUserService.getCurrentLoginUser().getUserName());
            lambdaUpdateWrapper.set(Comment::getUpdateTime,deleteTime);
            commentMapper.update(new Comment(),lambdaUpdateWrapper);
            return R.success();
        }
        LambdaQueryWrapper<Comment> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getPid,id);
        lambdaQueryWrapper.eq(Comment::getDelFlag,"0");
        List<Comment> commentList=commentMapper.selectList(lambdaQueryWrapper);
        if(commentList!=null){
            LambdaUpdateWrapper<Comment> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Comment::getPid,id);
            lambdaUpdateWrapper.set(Comment::getDelFlag,"1");
            lambdaUpdateWrapper.set(Comment::getUpdateBy,iUserService.getCurrentLoginUser().getUserName());
            lambdaUpdateWrapper.set(Comment::getUpdateTime,deleteTime);
            commentMapper.update(new Comment(),lambdaUpdateWrapper);
            return R.success();
        }
        return R.success();
    }

    @Override
    public R deleteByIds(Integer[] ids) {
        return null;
    }

    @Override
    public R queryArticleComments(Integer articleId) {
        List<Comment> articleComments = commentMapper.queryCommentDetail(articleId);
        System.out.println(articleComments);
        List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());
        for (Comment origin : originList) {
            List<Comment> comments = articleComments.stream().filter(comment -> origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            comments.forEach(comment -> {
                Optional<Comment> pComment = articleComments.stream().filter(comment1 -> comment.getPid().equals(comment1.getId())).findFirst();
                pComment.ifPresent(v -> {
                    comment.setPUserName(v.getUserName());
                    comment.setPUserId(v.getCommentatorId());
                });
            });
            origin.setReplies(commentMapper.selectRepliesByOriginId(origin.getId()));
            origin.setChildrenList(comments);
        }
        return R.success(originList);
    }
}
